window.onload = function () {
    cutByItem(1);
}

function cutByItem(pageNO) {
    axios.get("/em/cutByItem", {
        params: {
            pageNO,
            name: $("name").value,
            dept: $("dept").value,
        }
    }).then(resp => {
        var info = resp.data;
        var str = "";
        var pageStr = "";
        info.records.forEach(n => {
            str += `<tr><td><input type="checkbox" class="emIds" value="${n.emId}"></td>
                    <td>${n.relName}</td><td>${n.dept}</td><td>${n.position}</td>
                    </tr>`;
        })
        $("data").innerHTML = str;

        for (var i = 1; i <= info.pages; i++) {
            pageStr += `<a style="margin-left: 10px" href="javascript:cutByItem(${i})">${i}</a>`;
        }

        $("pageSpan").innerHTML = pageStr;
    });
}

function showEm() {
    $("addReceiver").style.visibility = "visible";
}

function add() {
    $("addReceiver").style.visibility = "hidden";
    let ids = document.getElementsByClassName("emIds");
    var idArray = [];
    for (let i = 0; i < ids.length; i++) {
        if (ids[i].checked) {
            idArray.push(ids[i].value);
        }
    }
    var paramsObj = new URLSearchParams();
    paramsObj.append("idArray", idArray);
    axios.post("/em/findByIds", paramsObj).then(resp => {
        var info = resp.data;
        var emStr = "";
        info.forEach(n => {
            emStr += `<tr><td>${n.name}</td><td>${n.dept}</td><td><a href="javascript:del(${n.emId})">删除</a></td></tr>`;
        })
        $("receivers").innerHTML = emStr;
    })
}

function del(id) {
    axios.get("/em/del", {
        params: {
            id
        }
    }).then(resp => {
        var info = resp.data;
        alert(info);
        var emStr = "";
        info.forEach(n => {
            emStr += `<tr><td>${n.name}</td><td>${n.dept}</td><td><a href="javascript:del(${n.emId})">删除</a></td></tr>`;
        })
        $("receivers").innerHTML = emStr;
    });
}

async function send() {
    let file;
    let formData = new FormData();
    formData.append("annex", $("annex").files[0]);
    let config = {
        headers: {'Content-Type': 'multipart/form-data'}
    }
    await axios.post("/upload", formData, config).then(resp => {
        file = resp.data;
    });

    axios.get("/mail/send",{
        params:{
            subject:$("subject").value,
            content:$("content").value,
            annex:file
        }
    }).then(resp => {
        if (resp.data == "ok"){
            location.href = "/mails/success.html";
        }
    });

}